package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.OrdersDao;
import com.ytjj.qmyx.admin.mapper.AdminMapper;
import com.ytjj.qmyx.admin.mapper.OrderProblemMessageMapper;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.OrderProblemMessage;
import com.ytjj.qmyx.admin.model.request.OrderProblemCommitRequest;
import com.ytjj.qmyx.admin.model.request.OrderProblemListRequest;
import com.ytjj.qmyx.admin.model.request.OrderProblemReplyRequest;
import com.ytjj.qmyx.admin.model.response.*;
import com.ytjj.qmyx.admin.model.response.order.OrderInfoResponse;
import com.ytjj.qmyx.admin.service.OrderProblemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderProblemServiceImpl implements OrderProblemService {
    @Resource
    private OrderProblemMessageMapper orderProblemMessageMapper;

    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private AdminMapper adminMapper;
    @Resource(name = "guchuangRabbitTemplate")
    private RabbitTemplate guchuangRabbitTemplate;

//    @Resource(name = "jumaiduoRabbitTemplate")
//    private RabbitTemplate jumaiduoRabbitTemplate;
//
//    @Resource(name = "yiquanRabbitTemplate")
//    private RabbitTemplate yiquanRabbitTemplate;
//
//    @Resource(name = "zxlpRabbitTemplate")
//    private RabbitTemplate zxlpRabbitTemplate;
//
//    @Resource(name = "ygyxRabbitTemplate")
//    private RabbitTemplate ygyxRabbitTemplate;
//
//    @Resource(name = "yxhdRabbitTemplate")
//    private RabbitTemplate yxhdRabbitTemplate;
//
//    @Resource(name = "jckjRabbitTemplate")
//    private RabbitTemplate jckjRabbitTemplate;

    @Resource
    private OrdersDao ordersDao;



    @Override
    public int commitProblem(OrderProblemCommitRequest request,Admin admin) {
        log.info("提交订单问题参数:{}==== adminId:{}",JSONObject.toJSONString(request),admin.getId());
        if (StringUtils.isEmpty(request.getContentImg()) &&  StringUtils.isEmpty(request.getContentVideo())
                && StringUtils.isEmpty(request.getContentText())) {
            throw new ApiException("提交问题的内容、图片、视频不能同时为空!!!");
        }
        request.setCommitUser(admin.getName());

        String resultStr = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/orderProblem/commitProblem",
                JSON.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonResult<Integer> commonResult = JSONObject.parseObject(resultStr, CommonResult.class);

        Integer problemId = null;
        if (null != commonResult && commonResult.getData() !=null) {
            problemId =  commonResult.getData();
        }
        List<Admin> customers = adminMapper.getAllRoleAdmin("DOCUMENTARY");
        if (!CollectionUtils.isEmpty(customers)) {
            for (Admin customer : customers) {
                //保存订单问题消息
                OrderProblemMessage orderProblemMessage = new OrderProblemMessage();
                orderProblemMessage.setCommitTime(new Date());
                orderProblemMessage.setCommitUser(admin.getId());
                orderProblemMessage.setContent(request.getContentText());
                orderProblemMessage.setReceiveUser(customer.getId());
                orderProblemMessage.setStatus(0);
                orderProblemMessage.setProblemStatus(1);
                orderProblemMessage.setProblemId(problemId);
                orderProblemMessage.setChildOrderNo(request.getChildOrderNo());
                orderProblemMessage.setProblemType(request.getProblemType());
                orderProblemMessage.setSupplyProductId(request.getSupplyProductId());
                orderProblemMessageMapper.insert(orderProblemMessage);
            }
        }
      return problemId;
    }

    @Override
    public int replyProblem(OrderProblemReplyRequest request,Admin admin) {
        log.info("订单问题回复参数:{}==== adminId:{}",JSONObject.toJSONString(request),admin.getId());
        if (StringUtils.isEmpty(request.getContentImg()) &&  StringUtils.isEmpty(request.getContentVideo())
                && StringUtils.isEmpty(request.getContentText())) {
            throw new ApiException("提交问题的内容、图片、视频不能同时为空!!!");
        }

        if (null != request.getReceiveUser()) {
            Admin receiveUser = adminMapper.selectByPrimaryKey(request.getReceiveUser());
            request.setReceiveUserName(receiveUser.getName());
        }
        request.setCommitUser(admin.getId());
        request.setCommitUserName(admin.getName());
        if (request.getProblemType()==1) {
            String beginChildOrderNo = request.getChildOrderNo().substring(0, 1);
            if ("NN".equals(beginChildOrderNo)) {
                sendOrderProblemMessage(guchuangRabbitTemplate,request);
            }
//            else if ("D".equals(beginChildOrderNo) ) {
//                sendOrderProblemMessage(jumaiduoRabbitTemplate,request);
//            } else if ("F".equals(beginChildOrderNo)) {
//                sendOrderProblemMessage(yiquanRabbitTemplate,request);
//            } else if("H".equals(beginChildOrderNo)) {
//                sendOrderProblemMessage(zxlpRabbitTemplate,request);
//            } else if ("O".equals(beginChildOrderNo)) {
//                sendOrderProblemMessage(ygyxRabbitTemplate,request);
//            } else if ("Q".equals(beginChildOrderNo)) {
//                sendOrderProblemMessage(yxhdRabbitTemplate,request);
//            } else if ("S".equals(beginChildOrderNo)) {
//                sendOrderProblemMessage(jckjRabbitTemplate,request);
//            }
        } else if (request.getProblemType()==2) {
            sendOrderProblemMessage(guchuangRabbitTemplate,request);
        }

        return 0;
    }


    private void sendOrderProblemMessage(RabbitTemplate rabbitTemplate, OrderProblemReplyRequest request) {
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/orderProblem/replyProblem",
                JSON.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
        if (null != commonResult && commonResult.getData() !=null) {
            OrderInteractRecords data =  JSONObject.parseObject(commonResult.getData().toString(),OrderInteractRecords.class);
            if (request.getReplyRole() == 2 &&  StringUtils.isEmpty(data.getReceiveUser())) {
                throw new ApiException("回复接收人不能为空!");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("commitUser",request.getCommitUser());
            requestMap.put("content",request.getContentText());
            requestMap.put("problemId",request.getProblemId());
            requestMap.put("commitTime",new Date());
            requestMap.put("status",0);
            requestMap.put("problemStatus",1);
            requestMap.put("childOrderNo",request.getChildOrderNo());
            requestMap.put("receiveUserName",data.getReceiveUser());
            requestMap.put("replyRole",request.getReplyRole());
            requestMap.put("problemType",request.getProblemType());
            requestMap.put("supplyProductId",request.getSupplyProductId());
            rabbitTemplate.convertAndSend(QueueConstants.ORDER_PROBLEM_REPLY, JSON.toJSONString(requestMap));
        }
    }

    @Override
    public Integer finishProblem(Integer id) {
        Map<String,String> map = new HashMap();
        map.put("id",id.toString());
        String s = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/orderProblem/finishProblem",
                map, supplyApiConfig.getHeadsMap());
        return   orderProblemMessageMapper.updateProblemStatus(id,2);
    }

    @Override
    public void updateDealStatus(Integer id, Integer dealStatus) {
        Map<String,String> map = new HashMap();
        map.put("id",id.toString());
        map.put("dealStatus",dealStatus.toString());
        String s = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/orderProblem/updateDealStatus",
                map, supplyApiConfig.getHeadsMap());

    }

    @Override
    public CommonPage<OrderProblemListResponse> orderProblemList(OrderProblemListRequest request) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/orderProblem/orderProblemList",
                JSON.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonPage commonPage = JSONObject.parseObject(resultJson, CommonPage.class);
        List<OrderProblemListResponse> list = JSONArray.parseArray(commonPage.getList().toString(), OrderProblemListResponse.class);
        commonPage.setList(list);
        return commonPage;
    }

    @Override
    public CommonResult<OrderProblemDetailResponse> orderProblemDetail(Integer id) {

        Map<String,String> map = new HashMap();
        map.put("id",id.toString());
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/orderProblem/orderProblemDetail",
                map, supplyApiConfig.getHeadsMap());

        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        OrderProblemDetailResponse orderProblemDetailResponse = JSONObject.parseObject(commonResult.getData().toString(), OrderProblemDetailResponse.class);
        return CommonResult.success(orderProblemDetailResponse);
    }

    @Override
    public List<Admin> getReceiveUser(Integer type) {
        List<Admin> customers = null;
        if (type == 1) {
            customers = adminMapper.getAllRoleAdmin("Customer");
        } else if (type == 2) {
            customers = adminMapper.getAllRoleAdmin("DOCUMENTARY");
        }
        return customers;
    }

    @Override
    public List<OrderProblemExportResponse> exportOrderProblemList(OrderProblemListRequest request) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/orderProblem/exportOrderProblemList",
                JSON.toJSONString(request), supplyApiConfig.getHeadsMap());
        List<OrderProblemExportResponse> responses = JSONObject.parseArray(resultJson, OrderProblemExportResponse.class);
        return responses;
    }

    @Override
    public void updateProblemUrgent(Integer id, Integer isUrgent) {
        Map<String,String> map = new HashMap();
        map.put("id",id.toString());
        map.put("isUrgent",isUrgent.toString());
        HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/orderProblem/updateProblemUrgent", map, supplyApiConfig.getHeadsMap());
    }
}
